﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace Landscape.Web.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:LandscapeFileUploader runat=server></{0}:LandscapeFileUploader>")]
    public class LandscapeFileUploader : WebControl
    {
        
        private RadGrid _rgAttList;
        private RadAsyncUpload _rasyncUpload;
        private HiddenField _hfJsObject;
        private HiddenField _hfDownloadFunction;
        private Panel _landscapePanel;
        private Table _landscapeTable;
        private Label _lblFileUpload;
        private Label _lblFileList;

        private string _ID = string.Empty;
        

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        public string TargetFolder
        {
            get
            {
                String s = (String)ViewState["_TargetFolder"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_TargetFolder"] = value;
            }
        }

        public string OnFileUploadRemoved
        {
            get
            {
                String s = (String)ViewState["_OnFileUploadRemovedFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnFileUploadRemovedFunc"] = value;
            }
        }

        public string OnFileUploadFailed
        {
            get
            {
                String s = (String)ViewState["_OnFileUploadFailedFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnFileUploadFailedFunc"] = value;
            }
        }

        public string OnFilesUploaded
        {
            get
            {
                String s = (String)ViewState["_OnFilesUploadedFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnFilesUploadedFunc"] = value;
            }
        }

        public string OnFileUploading
        {
            get
            {
                String s = (String)ViewState["_OnFileUploadingFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnFileUploadingFunc"] = value;
            }
        }

        public string OnGridCommand
        {
            get
            {
                String s = (String)ViewState["_OnGridCommandFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnGridCommandFunc"] = value;
            }
        }

        public string OnGridCreated
        {
            get
            {
                String s = (String)ViewState["_OnGridCreatedFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnGridCreatedFunc"] = value;
            }
        }

        public string OnGridRowDataBound
        {
            get
            {
                String s = (String)ViewState["_OnGridRowDataBoundFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnGridRowDataBoundFunc"] = value;
            }
        }

        public string OnGetData
        {
            get
            {
                String s = (String)ViewState["_OnGetDataFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnGetDataFunc"] = value;
            }
        }

        public string OnFileDownloadClick
        {
            get
            {
                String s = (String)ViewState["_OnFileDownloadClickFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnFileDownloadClickFunc"] = value;
            }
        }

        public string OnFileDeleteClick
        {
            get
            {
                String s = (String)ViewState["_OnFileDeleteClickFunc"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["_OnFileDeleteClickFunc"] = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            var padd = this.ID.Substring("LandscapeFileUploader".Length);

            this._hfDownloadFunction = new HiddenField();
            this._hfDownloadFunction.ID = "hfDownloadFunction_" + padd;

            this._rgAttList = new RadGrid();
            this._rgAttList.ID = "orgAttachmentList_" + padd;
            this._rgAttList.GridLines = GridLines.Horizontal;
            this._rgAttList.AllowPaging = true;
            this._rgAttList.ClientSettings.Selecting.AllowRowSelect = true;

            /*if (this.OnGridCommand != null && this.OnGridCommand.Trim() != string.Empty)
                this._rgAttList.ClientSettings.ClientEvents.OnCommand = this.OnGridCommand.Trim();*/

            this._rgAttList.ClientSettings.ClientEvents.OnCommand = "this._defaultGridCommand";

            /*if (this.OnGridRowDataBound != null && this.OnGridRowDataBound.Trim() != string.Empty)
                this._rgAttList.ClientSettings.ClientEvents.OnRowDataBound = this.OnGridRowDataBound.Trim();*/

            this._rgAttList.ClientSettings.ClientEvents.OnRowDataBound = "this._defaultRowDataBind";

            /*if (this.OnGridCreated != null && this.OnGridCreated.Trim() != string.Empty)
                this._rgAttList.ClientSettings.ClientEvents.OnGridCreated = this.OnGridCreated.Trim();*/

            this._rgAttList.ClientSettings.ClientEvents.OnGridCreated = "this._defaultGridCreated";

            GridBoundColumn clientCol = new GridBoundColumn();
            clientCol.HeaderText = "#";
            clientCol.UniqueName = "SelectColumn";
            this._rgAttList.Columns.Add(clientCol);

            GridBoundColumn titleCol = new GridBoundColumn();
            titleCol.HeaderText = "Title";
            titleCol.UniqueName = "TitleColumn";
            titleCol.DataField = "Title";
            this._rgAttList.Columns.Add(titleCol);

            GridBoundColumn fileNameCol = new GridBoundColumn();
            fileNameCol.HeaderText = "File Name";
            fileNameCol.UniqueName = "FileNameColumn";
            fileNameCol.DataField = "FileName";
            this._rgAttList.Columns.Add(fileNameCol);

            GridBoundColumn fileSizeCol = new GridBoundColumn();
            fileSizeCol.HeaderText = "File Size";
            fileSizeCol.UniqueName = "FileSizeColumn";
            fileSizeCol.DataField = "FileSize";
            this._rgAttList.Columns.Add(fileSizeCol);

            GridBoundColumn uploadUserNameCol = new GridBoundColumn();
            uploadUserNameCol.HeaderText = "Uploaded By";
            uploadUserNameCol.UniqueName = "UserNameColumn";
            uploadUserNameCol.DataField = "UploadUserName";
            this._rgAttList.Columns.Add(uploadUserNameCol);

            GridBoundColumn uploadDateCol = new GridBoundColumn();
            uploadDateCol.HeaderText = "Upload Date";
            uploadDateCol.UniqueName = "UploadDateColumn";
            uploadDateCol.DataField = "UploadDateString";
            this._rgAttList.Columns.Add(uploadDateCol);

            GridBoundColumn actionsCol = new GridBoundColumn();
            actionsCol.HeaderText = "Actions";
            actionsCol.UniqueName = "ActionsColumn";
            this._rgAttList.Columns.Add(actionsCol);
            
            this._rasyncUpload = new RadAsyncUpload();
            this._rasyncUpload.ID = "LandscapeFileUploader_" + padd;
            this._rasyncUpload.AutoAddFileInputs = true;
            this._rasyncUpload.HttpHandlerUrl = "~/Handlers/LandscapeAsyncFileUploader.ashx";
            this._rasyncUpload.MultipleFileSelection = Telerik.Web.UI.AsyncUpload.MultipleFileSelection.Automatic;
            this._rasyncUpload.TargetFolder = this.TargetFolder;

            if (this.OnFilesUploaded != null && this.OnFilesUploaded.Trim() != string.Empty)
                this._rasyncUpload.OnClientFilesUploaded = this.OnFilesUploaded.Trim();

            if (this.OnFileUploadFailed != null && this.OnFileUploadFailed.Trim() != string.Empty)
                this._rasyncUpload.OnClientFileUploadFailed = this.OnFileUploadFailed.Trim();

            if (this.OnFileUploadRemoved != null && this.OnFileUploadRemoved.Trim() != string.Empty)
                this._rasyncUpload.OnClientFileUploadRemoved = this.OnFileUploadRemoved.Trim();

            if (this.OnFileUploading != null && this.OnFileUploading.Trim() != string.Empty)
                this._rasyncUpload.OnClientFileUploading = this.OnFileUploading.Trim();

            this._hfJsObject = new HiddenField();
            this._hfJsObject.ID = "hfJSObject_" + padd;

            this._landscapeTable = new Table();
            this._landscapeTable.Rows.Add(new TableRow());
            this._landscapeTable.Rows[0].Cells.Add(new TableCell());
            this._lblFileUpload = new Label();
            this._lblFileUpload.Text = "Attach new files :";
            this._lblFileUpload.Font.Bold = true;

            this._landscapeTable.Rows[0].Cells[0].Controls.Add(this._lblFileUpload);

            this._landscapeTable.Rows.Add(new TableRow());
            this._landscapeTable.Rows[1].Cells.Add(new TableCell());
            this._landscapeTable.Rows[1].Cells[0].Controls.Add(this._rasyncUpload);
            this._landscapeTable.Rows[1].Cells[0].Controls.Add(this._hfJsObject);

            this._landscapeTable.Rows.Add(new TableRow());
            this._landscapeTable.Rows[2].Cells.Add(new TableCell());
            this._lblFileList = new Label();
            this._lblFileList.Text = "Attached Files :";
            this._lblFileList.Font.Bold = true;

            this._landscapeTable.Rows[2].Cells[0].Controls.Add(this._lblFileList);

            this._landscapeTable.Rows.Add(new TableRow());
            this._landscapeTable.Rows[3].Cells.Add(new TableCell());
            this._landscapeTable.Rows[3].Cells[0].Controls.Add(this._rgAttList);
            
            this._landscapePanel = new Panel();
            this._landscapePanel.ID = "LandscapeFileUploaderPanel_" + padd;
            this._landscapePanel.Controls.Add(this._landscapeTable);

            this.Controls.Add(this._landscapePanel);

            base.OnInit(e);
        }

        protected override void OnPreRender(EventArgs e)
        {   
            base.OnPreRender(e);
            string resourceName = "Landscape.Web.Controls.LandscapeFileUploader.js";

            ClientScriptManager cs = this.Page.ClientScript;
            cs.RegisterClientScriptResource(typeof(Landscape.Web.Controls.LandscapeFileUploader), resourceName);

            this._landscapePanel.ID = this.ClientID;
            this._landscapePanel.ClientIDMode = System.Web.UI.ClientIDMode.Static;

            string clientCallBacks = string.Empty;

            if (this.OnGridCreated != null && this.OnGridCreated.Trim() != string.Empty)
                clientCallBacks += "_ClientGridCreated : '" + this.OnGridCreated + "',";

            if (this.OnGridCommand != null && this.OnGridCommand.Trim() != string.Empty)
                clientCallBacks += "_ClientGridCommand : '" + this.OnGridCommand + "',";

            if (this.OnGridRowDataBound != null && this.OnGridRowDataBound.Trim() != string.Empty)
                clientCallBacks += "_ClientGridRowDataBound : '" + this.OnGridRowDataBound + "',";

            if (this.OnGetData != null && this.OnGetData.Trim() != string.Empty)
                clientCallBacks += "_ClientGetData : '" + this.OnGetData + "',";

            if (this.OnFileDeleteClick != null && this.OnFileDeleteClick.Trim() != string.Empty)
                clientCallBacks += "_ClientFileDeleteClick : '" + this.OnFileDeleteClick + "',";

            if (this.OnFileDownloadClick != null && this.OnFileDownloadClick.Trim() != string.Empty)
                clientCallBacks += "_ClientFileDownloadClick : '" + this.OnFileDownloadClick + "',";
            else
                clientCallBacks += "_ClientFileDownloadClick : 'downloadFile',";

            string jsFunctions = "funcs = {" + clientCallBacks + " GetUploader:function(){return $find(\"" + this._rasyncUpload.ClientID + "\");}, GetFileGrid:function(){return $find(\"" + this._rgAttList.ClientID + "\");}}";
            string defaultScript = "function _defaultRowDataBind(sender, args){$get(\"" + this.ClientID + "\").DefaultRowDataBind(sender, args);}";
            defaultScript += " function _defaultGridCreated(sender, args){$get(\"" + this.ClientID + "\").DefaultGridCreated(sender, args);}";
            defaultScript += " function _defaultGridCommand(sender, args){$get(\"" + this.ClientID + "\").DefaultGridCommand(sender, args);}";

            

            string script =
                "<SCRIPT type=text/javascript>Sys.Application.add_init(function () {"+ jsFunctions + "; $.extend($get(\"" + this.ClientID + "\"), LandscapeFileUploader); $.extend($get(\"" + this.ClientID + "\"), funcs);}); " + defaultScript + "</SCRIPT> ";
            //cs.RegisterClientScriptBlock(typeof(string), "LandscapeFileUploader", script);
            LiteralControl lc = new LiteralControl(script);
            this._landscapePanel.Controls.Add(lc);
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            //output.Write(Text);
            this._landscapePanel.RenderControl(output);
        }
    }
}
